<?php 

class SearchController extends Controller {

	protected $db;
	
	function __construct($db) {
		$this->db = $db;
		$viewItem = "search";
		if (isset($_GET['view'])) {
			$viewItem = $_GET['view'];
		}
		if ($viewItem == "search") {
			$movieList = false;
			$categories = $this->getCategories();
			if (isset($_POST['action'])) {
				if ($_POST['action'] == "save") {
					$movieList = $this->getMovies($_POST['categoryID'], $_POST['title'], $_POST['director']);
				}
			}
			
			$this->view = new SearchView();
			$this->view->setTitle("Search");
			$this->view->setCategoryList($categories);
			$this->view->setMovieList($movieList);
		}
		else if ($viewItem == "advanced_search") {
			$movieList = false;
			if (isset($_POST['action'])) {
				if ($_POST['action'] == "save") {
					$actor = $_POST['actor'];
					$ar = $_POST['ar'];
					$director = $_POST['director'];
					$dr = $_POST['dr'];
					$title = $_POST['title'];
					$tr = $_POST['tr'];
					$rating = $_POST['rating'];
					$orderBy = $_POST['orderby'];
					
					$movieList = $this->getEnhancedMovieList($actor, $director, $title, $rating, $ar, $dr, $tr, $orderBy);
				}
			}
			
			$this->view = new EnhancedSearchView();
			$this->view->setTitle("Advanced Search");
			$this->view->setMovieList($movieList);
		}
	}
	
	function getMovies($cat, $title, $director) {
		$results = $this->db->searchMovies($cat, $title, $director);
		$mList = array();
		$i=0;
		while ($row = $results->fetch_row()) {
			$movie = new Movie($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7], $row[8]);
			$mList[$i] = $movie;
			$i++;
		}
		return $mList;
	}
	
	function getCategories() {
		$results = $this->db->getCategories();
		$mList = array();
		$i=0;
		while ($row = $results->fetch_row()) {
			$cat = new Category($row[0], $row[1]);
			$mList[$i] = $cat;
			$i++;
		}
		return $mList;
	}
	
	function getEnhancedMovieList($actor, $director, $title, $rating, $ar, $dr, $tr, $orderBy) {
		$results = $this->db->getEnhancedMovies($actor, $director, $title, $rating, $ar, $dr, $tr, $orderBy);
		$mList = array();
		$i=0;
		if ($results) {
			while ($row = $results->fetch_row()) {
				$movie = new Movie($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7], $row[8]);
				$mList[$i] = $movie;
				$i++;
			}
			return $mList;
		}
	}
}